package com.wjm.client.controller;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.wjm.entity.Building;
import com.wjm.entity.Classroom;
import com.wjm.entity.Desk;
import com.wjm.entity.Record;
import com.wjm.entity.StuRecInfo;
import com.wjm.entity.Student;
import com.wjm.service.impl.BuildingServiceImpl;
import com.wjm.service.impl.ClassroomServiceImpl;
import com.wjm.service.impl.RecordServiceImpl;
import com.wjm.util.CacheUtil;
import com.wjm.util.JsonUtil;
import com.wjm.util.PropertiesUtil;
import com.wjm.util.StringUtil;

@Controller
@RequestMapping("/client/rec")
@SessionAttributes({ "student" })
public class RecordClientController {

	@Autowired
	private RecordServiceImpl recordService;

	@Resource(name = "buildingService")
	private BuildingServiceImpl buildingService;

	@Resource(name = "classroomService")
	private ClassroomServiceImpl classroomService;

	private final String recListKey = "recList";
	private final String pageKey = "page";

	@RequestMapping("/info")
	@ResponseBody
	public Map<String, Object> info(@ModelAttribute(StringUtil.STUDENT_KEY) Student stu, int current, int recStatus) {
		List<Record> list = null;
		int page = 0;
		Map<String, Object> map = new HashMap<>();
		try {
			Record rec = new Record();
			rec.setRecStatus(recStatus);
			rec.setStuId(stu.getStuId());
			int number = Integer.parseInt(PropertiesUtil.getValue(StringUtil.PER_PAGE_NUM));
			list = recordService.queryByPage(current, number, rec);
			page = recordService.queryTotalNum(rec) / number + 1;
			map.put(recListKey, list);
			map.put(pageKey, page);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return map;
	}

	@RequestMapping("")
	public String record(@ModelAttribute(StringUtil.STUDENT_KEY) Student stu, String res, Model model) {
		String result = "/client/rec/" + res;
		if (res == null || res.equals("")) {
			result = "/error";
		}
		try {

		} catch (Exception e) {
			result = "/error";
		}
		return result;
	}

	@RequestMapping("/cancel")
	@ResponseBody
	public String cancel(@ModelAttribute(StringUtil.STUDENT_KEY) Student stu, int recId) {
		String result = "{\"result\":\"fail\"}";
		try {
			Record rec = new Record();
			rec.setRecId(recId);
			rec.setStuId(stu.getStuId());
			// 取消代码是3
			rec.setRecStatus(3);
			if (recordService.update(rec) == true) {

				StuRecInfo info = CacheUtil.getStuRecInfos().get(stu.getStuNo());
				if (info == null) {
					info = new StuRecInfo();
					info.setCancel(recordService.queryCancel(stu.getStuId()));
					CacheUtil.getStuRecInfos().put(stu.getStuNo(), info);
				} else {
					info.setCancel(info.getCancel() + 1);
				}
				info.setIsHave(false);

				// 如果取消预约所在的教室处在不可用队列，则需要将其放入可用
				for (Map.Entry<Integer, Record> entry : CacheUtil.getRecords().entrySet()) {
					if (entry.getValue().getRecId() == recId) {
						classroomService.checkUse(entry.getValue().getCrId());
						// 将取消的预约信息从缓存中清除
						CacheUtil.getRecords().get(entry.getValue().getDeskId());
						break;
					}
				}

				result = "{\"result\":\"success\"}";
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	@RequestMapping("/getRec")
	@ResponseBody
	public Record random(@ModelAttribute(StringUtil.STUDENT_KEY) Student student, int buId) {
		Record result = null;
		try {
			Date date = new Date();
			int hour = date.getHours();
			StuRecInfo info = CacheUtil.getStuRecInfos().get(student.getStuNo());
			// 判断今天是否预约或者超过次数
			if ((hour >= 7 && hour < 20) && (info == null || (info.getCancel() <= 5 && info.getIsHave() == false))) {
				Building building = CacheUtil.getBuildings().get(buId);
				// 如果传来的buId为0则选取第一个可用教学楼获取预约
				if (buId == 0) {
					for (Map.Entry<Integer, Building> entry : CacheUtil.getBuildings().entrySet()) {
						if (entry.getValue().getBuStatus() == 1) {
							building = entry.getValue();
							break;
						}
					}
				}
				List<Classroom> rooms = CacheUtil.getUseroom().get(buId);
				if (rooms != null) {
					SimpleDateFormat sdf = new SimpleDateFormat(StringUtil.TIME_FORMAT);
					// 此处的随机 可以优化 ，可以限制循环查找的次数，保证系统可靠
					for (Classroom room : rooms) {
						List<Desk> desks = CacheUtil.getDesks().get(room.getCrId());
						for (int i = 0; i < desks.size(); i++) {
							Desk desk = desks.get(i);
							// 判断该座位是否被预约
							if (CacheUtil.getRecords().get(desk.getDeskId()) == null) {
								Record record = new Record();
								record.setBuName(building.getBuName());
								record.setCrId(room.getCrId());
								record.setCrNo(room.getCrNo());
								record.setDeskId(desk.getDeskId());
								record.setDeskNo(desk.getDeskNo());
								record.setRecDate(sdf.format(new Date()));
								record.setStuId(student.getStuId());
								record.setStuName(student.getStuName());
								record.setStuNo(student.getStuNo());
								System.out.println(student.getStuNo());
								// 添加成功（缓存中更新在service中）
								if (recordService.save(record)) {
									result = record;
									classroomService.checkUnuse(record.getCrId(), buId);
									// 如果是空那么查询
									if (info == null) {
										info = new StuRecInfo();
										info.setCancel(recordService.queryCancel(student.getStuId()));
										CacheUtil.getStuRecInfos().put(student.getStuNo(), info);
									}
									// 表明已经有预约
									info.setIsHave(true);
									break;
								}
							}
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	@RequestMapping("/add")
	@ResponseBody
	public Record add(@ModelAttribute(StringUtil.STUDENT_KEY) Student student, Record record, int buId) {
		Record result = null;
		try {
			Date date = new Date();
			int hour = date.getHours();
			StuRecInfo info = CacheUtil.getStuRecInfos().get(student.getStuNo());
			// 判断预约情况，和上面情况一致
			if ((hour >= 7 && hour < 20) && (info == null || (info.getCancel() <= 5 && info.getIsHave() == false))) {
				if (CacheUtil.getRecords().get(record.getDeskId()) == null) {
					SimpleDateFormat sdf = new SimpleDateFormat(StringUtil.TIME_FORMAT);
					record.setBuName(CacheUtil.getBuildings().get(buId).getBuName());
					record.setRecDate(sdf.format(new Date()));
					record.setStuId(student.getStuId());
					record.setStuName(student.getStuName());
					record.setStuNo(student.getStuNo());
					// 添加成功（缓存中更新在service中）
					if (recordService.save(record)) {
						classroomService.checkUnuse(record.getCrId(), buId);
						result = record;
						if (info == null) {
							info = new StuRecInfo();
							info.setCancel(recordService.queryCancel(student.getStuId()));
							CacheUtil.getStuRecInfos().put(student.getStuNo(), info);
						}
						info.setIsHave(true);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println(JsonUtil.getJson(record));
		System.out.println(result);
		return result;
	}
}
